package liang.eight.edition.model.view.controller;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JColorChooser;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;

public class Controller extends JPanel implements ChangeListener {

	private Model model;

	private JTextField jtfRadius = new JTextField();

	private JComboBox jcboFilled = new JComboBox(new Boolean[] { new Boolean(false), new Boolean(true) });

	private JColorChooser colorChooser = new JColorChooser();

	/** Creates new form CircleController */
	public Controller() {
		// Panel to group labels
		JPanel panel1 = new JPanel();
		panel1.setLayout(new GridLayout(3, 1));
		panel1.add(new JLabel("Radius"));
		panel1.add(new JLabel("Filled"));
		panel1.add(new JLabel("Color"));

		// Panel to group text field, combo box, and another panel
		JPanel panel2 = new JPanel();
		panel2.setLayout(new GridLayout(3, 1));
		panel2.add(jtfRadius);
		panel2.add(jcboFilled);
		panel2.add(colorChooser);

		setLayout(new BorderLayout());
		add(panel1, BorderLayout.WEST);
		add(panel2, BorderLayout.CENTER);

		// Register listeners
		jtfRadius.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				if (model == null)
					return; // No model associated yet. Do nothing
				model.setRadius(new Double(jtfRadius.getText()).doubleValue());
			}
		});
		jcboFilled.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				if (model == null)
					return; // No model associated yet. Do nothing
				model.setFilled(((Boolean) jcboFilled.getSelectedItem()).booleanValue());
			}
		});
		colorChooser.getSelectionModel().addChangeListener(this);
	}

	public void setModel(Model newModel) {
		model = newModel;
	}

	public Model getModel() {
		return model;
	}

	@Override
	public void stateChanged(ChangeEvent e) {
		Color newColor = colorChooser.getColor();
		model.setColor(newColor);
	}
}
